<template>
  <div class="playback">
    <el-checkbox-group v-model="checkFlightList">
      <el-checkbox v-for="item in flightList" :key="item.id" :value="item.id" class="flight-item"
        @click="handleFlightChange(item)">
        <div class="flight-content">
          <div class="flight-id">{{ item.name }}</div>
          <div class="flight-info">
            <span>{{item.time||"暂无时间"}}</span>
          </div>
          <div class="flight-tag">历史轨迹</div>
        </div>
      </el-checkbox>
    </el-checkbox-group>

    <div v-if="flightList.length === 0" class="empty-state">
      <i class="el-icon-warning-outline"></i>
      <span>暂无架次数据</span>
    </div>
  </div>
</template>

<script setup>
import { getAssets } from "@/utils/index.ts"
import { nextTick, onMounted, ref, watch } from "vue"
import { ElMessage, ElLoading } from 'element-plus'
import mapStore from "@/stores/modules/map.ts"
import { getFlights, getHistory } from "@/api/planeReplayData/index.ts"
import { mapApi } from '@/components/cme-mapboxCore/api/mapApi.ts'
import moment from "moment"

const props = defineProps(['olService'])
const mapStores = mapStore()
const checkFlightList = ref([]) // 选中的架次列表
const flightList = ref([]) // 所有架次列表
const selectedFlights = ref([]) // 已选择的架次
const timeOption = ref({
  startTime: Number.MAX_VALUE,
  endTime: 0
})
const fightTimeList = ref([]) // 架次时间轴列表

/**
 * 获取今日架次数据
 */
const getTodaysFlights = async () => {
  try {
    const res = await getFlights()
    if (res.code === 200) {
      // 过滤非活动架次并格式化数据
      flightList.value = res.data
        .filter(item => !item.active)
        .map(item => ({
          id: item.flight,
          name: item.flight,
          time: moment(item.epoch).format('YYYY-MM-DD HH:mm:ss')
        }))
    }
  } catch (error) {
    ElMessage.error('获取架次数据失败')
    console.error('获取架次数据失败:', error)
  }
}

/**
 * 处理架次选择变更
 */
const handleFlightChange = async (flight) => {
  const isSelected = checkFlightList.value.includes(flight.id)
  isSelected ? await handleFlightDeselect(flight) : await handleFlightSelect(flight)
}

/**
 * 处理取消选择架次
 */
const handleFlightDeselect = async (flight) => {
  console.log(flight.id)
  delFightTimeLine(flight.id)
  selectedFlights.value = selectedFlights.value.filter(id => id !== flight.id)
  // 清除轨迹
  mapApi.modelMove.removeCallPlayBackModel(flight.id)
}

/**
 * 处理选择架次
 */
const handleFlightSelect = async (flight) => {
  selectedFlights.value.push(flight.id)
  await getPlanData(flight.id)
}

/**
 * 获取架次轨迹数据
 */
const getPlanData = async (id) => {
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在加载轨迹数据...',
    background: 'rgba(255, 255, 255, 0.4)',
  })

  try {
    const res = await getHistory({ flights: selectedFlights.value.join(',') })
    if (res.code === 200) {
      nextTick(() => {
        mapApi.modelMove.callPlayBackLoadModell(res.data)
      })
      
      // 更新时间轴
      const [startTime, endTime] = res.data.clock.interval.split('/')
      addFightTimeLine(id, startTime, endTime)
    }
  } catch (error) {
    console.error('获取轨迹数据失败:', error)
    ElMessage.error('获取轨迹数据失败')
  } finally {
    loadingInstance.close()
  }
}

// 时间轴管理
const addFightTimeLine = (id, startTime, endTime) => {
  fightTimeList.value.push({ id, startTime, endTime })
  timeOption.value.startTime = Math.min(startTime, timeOption.value.startTime)
  timeOption.value.endTime = Math.max(endTime, timeOption.value.endTime)
  mapStores.setTime(timeOption.value)
}

const delFightTimeLine = (id) => {
  const remainingFlights = fightTimeList.value.filter(item => item.id !== id)
  fightTimeList.value = remainingFlights

  if (remainingFlights.length === 0) {
    resetTimeOption()
    return
  }

  updateTimeOptionFromRemainingFlights(remainingFlights)
}

const resetTimeOption = () => {
  timeOption.value = {
    startTime: Number.MAX_VALUE,
    endTime: 0
  }
  mapStores.clearTimeAxis()
}

const updateTimeOptionFromRemainingFlights = (flights) => {
  timeOption.value = {
    startTime: Math.min(...flights.map(f => f.startTime)),
    endTime: Math.max(...flights.map(f => f.endTime))
  }
  mapStores.setTime(timeOption.value)
}

// 清除所有回放轨迹
const clearPlaybackAll = () => {
  // 清除所有轨迹
  checkFlightList.value.map(item => {
    mapApi.modelMove.removeCallPlayBackModel(item)
  })
  checkFlightList.value = []
  fightTimeList.value = []
  resetTimeOption()
}

// 生命周期钩子
onMounted(() => {
  // 初始化地图类型
  mapStores.pushMapType('layerPlayBack')
})

// 监听时间轴参数变化
watch(() => mapStores.timelineParameters, (newVal) => {
  // TODO: 实现回放移动逻辑
})

// 导出方法供父组件使用
defineExpose({
  clearPlaybackAll,
  getTodaysFlights
})
</script>

<style lang="scss" scoped>
.playback {
  height: 100%;
  padding: 12px;
  overflow-y: auto;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background: rgba(144, 147, 153, 0.3);
    border-radius: 3px;
    transition: all 0.3s ease;

    &:hover {
      background: rgba(144, 147, 153, 0.5);
    }
  }

  &::-webkit-scrollbar-track {
    background: transparent;
  }
}

.flight-item {
  height: auto;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8px;
  margin-right: 0;
  transition: transform 0.2s ease;

  &:hover {
    transform: translateX(2px);
  }

  :deep(.el-checkbox) {
    display: flex;
    margin: 0;
    padding: 0;
    height: auto;
  }

  :deep(.el-checkbox__input) {
    margin: 12px 0 0 10px;
  }

  :deep(.el-checkbox__label) {
    padding: 0;
    flex: 1;
  }
}

.flight-content {
  position: relative;
  margin-left: 10px;
  padding: 10px 12px;
  box-sizing: border-box;
  background: rgba(246, 248, 252, 0.7);
  border-radius: 8px;
  transition: all 0.3s ease;
  border: 1px solid rgba(67, 126, 241, 0.1);

  &:hover {
    background: rgba(238, 241, 248, 0.9);
    border-color: rgba(67, 126, 241, 0.2);
    box-shadow: 0 4px 12px rgba(67, 126, 241, 0.08);
  }
}

.flight-id {
  font-size: 14px;
  font-weight: 500;
  color: #2c3e50;
  margin-bottom: 6px;
  padding-right: 70px;
  line-height: 1.3;
}

.flight-info {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #909399;
  line-height: 1.3;

  span {
    display: flex;
    align-items: center;
  }
}

.flight-tag {
  position: absolute;
  top: 10px;
  right: 10px;
  padding: 2px 8px;
  font-size: 12px;
  color: #437EF1;
  background: rgba(67, 126, 241, 0.1);
  border-radius: 6px;
  white-space: nowrap;
  backdrop-filter: blur(4px);
  transition: all 0.3s ease;

  &:hover {
    background: rgba(67, 126, 241, 0.15);
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
  color: #909399;
  opacity: 0.7;
  transition: opacity 0.3s ease;

  &:hover {
    opacity: 0.9;
  }

  i {
    font-size: 32px;
    margin-bottom: 12px;
    color: #437EF1;
    opacity: 0.5;
  }

  span {
    font-size: 14px;
  }
}
</style>